package com.jeffers.videorecord;

import android.content.DialogInterface;
import android.graphics.SurfaceTexture;
import android.hardware.Camera;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class NativeVideoRecordFragment extends Fragment implements MediaRecorder.OnErrorListener {

	private static final String TAG = "NativeVideoRecordFragment";

	@Bind(R.id.camera_preview)
	TextureView mTextureView;
	private SurfaceTexture mSurfaceTexture;
	private MediaRecorder mMediaRecorder;
	private Camera mCamera;
	private CamcorderProfile mVideoProfile;

	@Bind(R.id.drawer_layout)
	DrawerLayout mDrawerLayout;

	@Bind(R.id.start_record)
	Button mStartRecordBtn;
	@Bind(R.id.stop_record)
	Button mStopRecordBtn;
	// record video profile
	@Bind(R.id.video_frame_rate)
	EditText mVideoFrameRateTxt;
	@Bind(R.id.video_frame_width)
	EditText mVideoFrameWidthTxt;
	@Bind(R.id.video_frame_height)
	EditText mVideoFrameHeightTxt;
	// Preview Size
	@Bind(R.id.preview_height)
	EditText mPreviewHeightTxt;
	@Bind(R.id.preview_width)
	EditText mPreviewWidthTxt;


	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		getActivity().getWindow().clearFlags(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
		getActivity().getWindow().addFlags(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragment_native_video_record,container,false);
		ButterKnife.bind(this, rootView);
		initSurfaceView();
		return rootView;
	}

	private void initSurfaceView(){


		mStopRecordBtn.setEnabled(false);
		mVideoProfile = CamcorderProfile.get(CamcorderProfile.QUALITY_720P);
		mVideoProfile.videoCodec = MediaRecorder.VideoEncoder.MPEG_4_SP;
		mVideoFrameRateTxt.setText(String.valueOf(mVideoProfile.videoFrameRate));
		mVideoFrameWidthTxt.setText(String.valueOf(mVideoProfile.videoFrameWidth));
		mVideoFrameHeightTxt.setText(String.valueOf(mVideoProfile.videoFrameHeight));

		mTextureView.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() {
			@Override
			public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
				Log.d(TAG, String.format("TextureSize width %s height %s", width, height));
				mSurfaceTexture = surface;
				mPreviewWidthTxt.setText(String.valueOf(width));
				mPreviewHeightTxt.setText(String.valueOf(height));
				initCamera();
			}

			@Override
			public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
				Log.d(TAG, String.format("TextureSize width %s height %s", width, height));
				mSurfaceTexture = surface;
			}

			@Override
			public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
				mSurfaceTexture = null;
				stopCamera();
				return false;
			}

			@Override
			public void onSurfaceTextureUpdated(SurfaceTexture surface) {

			}
		});
	}

	@OnClick(R.id.start_record)
	public void clickStartRecord(){
		startRecord();
	}

	@OnClick(R.id.stop_record)
	public void clickStopRecord(){
		stopRecord();
	}

	@OnClick(R.id.video_config)
	public void clickVideoConfig(){
		mDrawerLayout.closeDrawers();
		configViewProfile();
		layoutPreView();
	}

	private void initCamera(){
		if(mCamera == null){
			mCamera = Camera.open();
			Camera.Parameters parameters = mCamera.getParameters();
			parameters.setRotation(90);
			List<Camera.Size> previewSizes =  parameters.getSupportedPreviewSizes();
			for(Camera.Size size : previewSizes) {
				Log.d(TAG, String.format("Support Preview Width %s , Height %s",size.width,size.height));
			}
			List<Camera.Size> videoSizes = parameters.getSupportedVideoSizes();
			for(Camera.Size size : videoSizes) {
				Log.d(TAG, String.format("Support Video Width %s , Height %s",size.width,size.height));
			}
			if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1){
				//关闭录像提示音
				mCamera.enableShutterSound(false);
			}
			//设置合适的Preview size
			Camera.Size size = CameraSizeUtils.getPictureSize(parameters.getSupportedPreviewSizes(), mTextureView.getWidth());
			parameters.setPreviewSize(size.width, size.height);
			mCamera.setParameters(parameters);
			mCamera.setDisplayOrientation(90);
			try {
				mCamera.setPreviewTexture(mSurfaceTexture);
				mCamera.startPreview();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	private void stopCamera() {
		if (mCamera != null) {
			mCamera.stopPreview();
			mCamera.release();
			mCamera = null;
		}
	}

	/**
	 * 参考官网 http://developer.android.com/intl/zh-tw/guide/topics/media/camera.html#capture-video
	 */
	private void startRecord(){
		if(mCamera == null){
			return;
		}
		Log.d(TAG, "startRecord ");
		if(mMediaRecorder == null){
			mMediaRecorder = new MediaRecorder();
			mMediaRecorder.setOnErrorListener(this);
		}else{
			mMediaRecorder.reset();
		}

		// Step 1: Unlock and set camera to MediaRecorder
		mCamera.unlock();
		mMediaRecorder.setCamera(mCamera);

		// Step 2: Set sources
		mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
		mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);

		// Step 3: Set a CamcorderProfile (requires API Level 8 or higher)
		mMediaRecorder.setProfile(mVideoProfile);

		/*//Step 3.1 设置视频录制输出格式：THREE_GP、MPEG_4、RAW_AWR、Default
		mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
		//Step 3.2 设置音频编码
		mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
		//Step 3.3 设置视频录制输出编码:H263、H264、VP8、MPEG_4_SP
		mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H263);
		//设置视频大小
		mMediaRecorder.setVideoSize(480, 800);
		//设置视频帧率
		mMediaRecorder.setVideoFrameRate(30);*/

		// Step 4: Set output file
		File videoFile = null;
		try {
			// Video_yyyyMMddhhmmss.mp4
			String fileName = String.format("Video_%1$tY%1$tm%1$td%1$tH%1$tM%1$tS.mp4", new Date());
			videoFile = new File(getActivity().getExternalCacheDir(),fileName);
			videoFile.createNewFile();
		} catch (IOException e) {
			e.printStackTrace();
		}

		//设置路径
		if(videoFile.exists()) {
			Log.d(TAG, "setOutputFile " + videoFile);
			mMediaRecorder.setOutputFile(videoFile.getAbsolutePath());
		}

		//Step 5: Set the preview output
		mMediaRecorder.setPreviewDisplay(new Surface(mSurfaceTexture));


		// Step 6: Prepare configured MediaRecorder
		try {
			//改变输出视频的方向
			mMediaRecorder.setOrientationHint(90);
			mMediaRecorder.prepare();
			mMediaRecorder.start();
			mStopRecordBtn.setEnabled(true);
			mStartRecordBtn.setEnabled(false);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void stopRecord(){
		if(mMediaRecorder != null){
			mMediaRecorder.stop();
			mMediaRecorder.release();
			mMediaRecorder = null;
			mCamera.lock();

			mStopRecordBtn.setEnabled(false);
			mStartRecordBtn.setEnabled(true);
		}
		if(mCamera != null){
			try {
				mCamera.reconnect();
				mCamera.startPreview();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
		stopRecord();
	}

	@Override
	public void onError(MediaRecorder mr, int what, int extra) {

	}

	private void layoutPreView() {
		ViewGroup.LayoutParams videoPreviewLayoutParams = mTextureView.getLayoutParams();
		// mDisplayMetrics.widthPixels
		int w = Integer.valueOf(mPreviewWidthTxt.getText().toString());
		int h = Integer.valueOf(mPreviewHeightTxt.getText().toString());
		videoPreviewLayoutParams.width = w;
		videoPreviewLayoutParams.height = h;
		mTextureView.setLayoutParams(videoPreviewLayoutParams);
		cameraPreviewSize(w);
	}

	private void cameraPreviewSize(int w){
		Camera.Parameters parameters = mCamera.getParameters();
		Camera.Size size = CameraSizeUtils.getPictureSize(parameters.getSupportedPreviewSizes(), w);
		parameters.setPreviewSize(size.width,size.height);
		mCamera.setParameters(parameters);
	}

	private void showConfigureAlert(){
		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

		View dialogView = getActivity().getLayoutInflater().inflate(R.layout.video_config, (ViewGroup) getView(),false);
		final EditText videoFrameRate = ButterKnife.findById(dialogView, R.id.video_frame_rate);
		final EditText videoFrameWidth = ButterKnife.findById(dialogView, R.id.video_frame_width);
		final EditText videoFrameHeight = ButterKnife.findById(dialogView,R.id.video_frame_height);
		videoFrameRate.setText(String.valueOf(mVideoProfile.videoFrameRate));
		videoFrameWidth.setText(String.valueOf(mVideoProfile.videoFrameWidth));
		videoFrameHeight.setText(String.valueOf(mVideoProfile.videoFrameHeight));
		builder.setView(dialogView);
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
			}
		});
		builder.setNegativeButton("取消", null);
		builder.show();
	}

	private void configViewProfile(){
		mVideoProfile.videoFrameRate = Integer.valueOf(mVideoFrameRateTxt.getText().toString());
		mVideoProfile.videoFrameWidth = Integer.valueOf(mVideoFrameWidthTxt.getText().toString());
		mVideoProfile.videoFrameHeight = Integer.valueOf(mVideoFrameHeightTxt.getText().toString());
	}


}